#include "auditapi.h"

#include <time.h>

#include <QString>
#include <QDebug>
#include <QDir>

#include "api/apiinit.h"
#include "sql/oesupermanagersqldatabase.h"
#include "sql/oeloginsqldatabase.h"


// 最后的错误信息
QString g_lastError;

// 密语列表 默认2048个
QList<QString> g_listCryptolalia;


QMap<QString,void*> g_mapCallbak;
extern OELoginSqlDatabase g_db;

AUDITAPISHARED_EXPORT int apiInit(void) {
    // 初始化 qrc 资源文件
    Q_INIT_RESOURCE(res);

    int ret = 0;

    /// [1] 初始化目录结构
//    QDir dir;
//    QString current_path = QDir::currentPath();


    /// [2] 检查本地数据库文件
    ret = OESuperManagerSqlDatabase::registerDB("auditapi.db", ":/sql/auditapi");

    if (0 != ret)
        ret = g_db.open("auditapi.db");



    return ret;
}

AUDITAPISHARED_EXPORT int apiUninit(void) {
    int ret = g_db.close();
    return ret;
}

AUDITAPISHARED_EXPORT int setCallBack(const char* const _object, void *_callback)
{
    g_mapCallbak[_object] = _callback;
    return 0;
}


AUDITAPISHARED_EXPORT int apiRandChinese(__api_in int _num,
                      __api_in int _randSeed,
                      __api_out char *_ch,
                      __api_out int *_size) {
    if (_num <= 0 || _ch == Q_NULLPTR)
        return 87;


    // 加载密语
    if(g_listCryptolalia.isEmpty()) {
        int temp_ret = apiLoadCryptolalia(g_listCryptolalia);

        if (g_listCryptolalia.isEmpty()) {
            return temp_ret;
        }
    }

    // 设置种子
    if (0 == _randSeed)
        srand(time(Q_NULLPTR));
    else
        srand(_randSeed);


    // 获得密语
    int ch_idx = 0;
    for (int i = 0; i < _num; ++i) {
        // rand_idx 得到随机密语
        int rand_idx = (rand()+clock()) % g_listCryptolalia.count();
        QString temp_chinese = g_listCryptolalia.at(rand_idx);

        // 转换密语到 _ch 中
        char* temp_ch = temp_chinese.toUtf8().data();
        int temp_ch_size = temp_chinese.toUtf8().length();
        memcpy(&_ch[ch_idx],temp_ch, temp_ch_size);
        ch_idx += temp_ch_size;
    }

    if (_size != Q_NULLPTR)
        *_size = ch_idx;

    return 0;
}


